Program to Convert Binary to Decimal in Java | 您所在的位置:网站首页 › convert binary to hexadecimal manually › Program to Convert Binary to Decimal in Java |
Here you will get program to convert binary to decimal in Java. There are mainly two ways to convert a binary number to decimal number in Java. 1. By using parseInt() method of Integer class.2. By using user defined logic. Program to Convert Binary to Decimal in JavaBy using Integer.parseInt() Integer.parseInt() method takes two arguments. First argument is a string and second argument is the base or radix in which we have to convert the number. The output is the integer represented by the string argument in the specified radix. Below is the program for it. 123456789101112131415import java.util.Scanner; class BinaryToDecimal{ public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter a binary number:"); String n=s.nextLine(); System.out.println(Integer.parseInt(n,2)); }}
Without using Integer.parseInt() In this method we have to define our own logic for converting binary number to decimal. The approach that we will use here is mentioned in below example. Image Source The program that implements above approach is mentioned below. 1234567891011121314151617181920212223import java.util.Scanner; class BinaryToDecimal{ public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.println("Enter a binary number:"); int n=s.nextInt(); int decimal=0,p=0; while(n!=0) { decimal+=((n%10)*Math.pow(2,p)); n=n/10; p++; } System.out.println(decimal); }}
Output
|
CopyRight 2018-2019 实验室设备网 版权所有 |